package com.handbook;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.Arrays;
import java.util.Random;

public class ProxyTest {

    public static void main(String[] args) {
        Object[] objects = new Object[100];
        for (int i = 0; i < objects.length; i++) {
           Integer value = i + 1;
           TraceHandler traceHandler = new TraceHandler(value);
           Object proxy = Proxy.newProxyInstance
                   (ClassLoader.getSystemClassLoader(), new Class[]{Comparable.class}, traceHandler);
           objects[i] = proxy;
        }

        int key = new Random().nextInt(objects.length);
        System.out.println("选择的key是 " + key);
        int i = Arrays.binarySearch(objects, key);
        System.out.println("位置为 ：" + i);
        Arrays.toString(objects);

    }
}

class TraceHandler implements InvocationHandler {

    private Object target;

    public TraceHandler(Object target) {
        this.target = target;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        System.out.println(target);
        System.out.println("method name: " + method.getName());
        if (args != null) {
            for (int i = 0; i < args.length; i++) {
                Object arg = args[i];
                System.out.println("参数是 ：" + arg + " ");
            }
        }
        return method.invoke(target, args);
    }

}